package com.zdf.license.web.controller;

import com.zdf.license.verify.service.LicenseVerifyService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.InputStream;
import java.util.Objects;

@Controller
@AllArgsConstructor
public class IndexController {

    private final LicenseVerifyService licenseVerifyService;

    /**
     * redirect
     */
    @GetMapping("/")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("licenseAuthInfo", licenseVerifyService.licenseAuthInfo());
        return modelAndView;
    }

    /**
     * 将申请码转化为真实数据
     * @param file 证书文件
     * @return AjaxResult
     */
    @PostMapping("/update")
    public ModelAndView update(MultipartFile file){
        ModelAndView modelAndView = new ModelAndView();
        if(file==null){
            modelAndView.setViewName("error/error");
            modelAndView.addObject("error", "检查错误");
            modelAndView.addObject("message", "检查文件合法性");
            return modelAndView;
        }
        String originalFilename = Objects.requireNonNull(file.getOriginalFilename());
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        if(!(extension.equals("lic"))){
            modelAndView.setViewName("error/error");
            modelAndView.addObject("error", "检查错误");
            modelAndView.addObject("message", "检查文件类型");
            return modelAndView;
        }
        try (InputStream is = file.getInputStream()) {
            licenseVerifyService.updateLicense(is);
            modelAndView.setViewName("index");
            modelAndView.addObject("licenseAuthInfo", licenseVerifyService.licenseAuthInfo());
            modelAndView.addObject("message", "更新成功");
            return modelAndView;
        } catch (Exception e) {
            modelAndView.setViewName("error/error");
            modelAndView.addObject("error", "内部错误");
            modelAndView.addObject("message", e.getMessage());
            return modelAndView;
        }
    }

}
